package com.example.jpademo.Controller;

import com.example.jpademo.Entity.Author;
import com.example.jpademo.Entity.Paper;
import com.example.jpademo.Service.PaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class PaperController {
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd/");
    @Autowired
    PaperService paperService;

    //增
    @PostMapping("/upload")
    public Paper upload(MultipartFile uploadFile, HttpServletRequest req)
    {
        //String savepath="D://paper//";
        String realPath=req.getSession().getServletContext().getRealPath("/paper/");
        String format=sdf.format(new Date());
        File folder=new File(realPath+format);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String oldName=uploadFile.getOriginalFilename();
        String newName= UUID.randomUUID().toString()+
                oldName.substring(oldName.lastIndexOf("."),oldName.length());
        try{
            uploadFile.transferTo(new File(folder, newName));
            String filePath=req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()
                    +"/paper/"+format+newName;
            Paper paper=new Paper();
            paper.setPath(filePath);
            paper.setTitle(oldName);
            paperService.addPaper(paper);
            return paper;
            //返回绝对路径
            //return folder.getAbsolutePath();
        }catch (IOException e){
            e.printStackTrace();
        }
        //???
        return null;
    }
    //查
    @GetMapping("/findAllPaper")
    public List<Paper> findAll(){
        return paperService.getAllPaper();
    }
}
